package com.emm.yixun.customer.service.impl.app.manage;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.ProcessInstanceHistoryLog;
import org.activiti.engine.task.Comment;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.mapper.BaseCodeValueMapper;
import com.emm.yixun.basic.mapper.PriceSchemeDetailMapper;
import com.emm.yixun.basic.mapper.PriceSchemeMapper;
import com.emm.yixun.basic.service.AuditService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.FamilyMemberService;
import com.emm.yixun.basic.service.HaveReceiveRefundService;
import com.emm.yixun.basic.service.ImageService;
import com.emm.yixun.basic.service.NeedReceiveRefundService;
import com.emm.yixun.basic.service.PayDepositService;
import com.emm.yixun.basic.service.PriceSchemeDetailService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.SignedService;
import com.emm.yixun.basic.service.SubscribeService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.GetPayDepositDetailReqDto;
import com.emm.yixun.common.app.GetPayDepositDetailResDto;
import com.emm.yixun.common.app.servletentity.AnnexListRes;
import com.emm.yixun.common.app.servletentity.CustomerFamilyListRes;
import com.emm.yixun.common.app.servletentity.HistoryTaskInfoListRes;
import com.emm.yixun.common.app.servletentity.ImageListRes;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.FamilyMember;
import com.emm.yixun.common.model.HaveReceiveRefund;
import com.emm.yixun.common.model.Image;
import com.emm.yixun.common.model.NeedReceiveRefund;
import com.emm.yixun.common.model.PriceScheme;
import com.emm.yixun.common.model.PriceSchemeDetail;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.Signed;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.FamilyMemberDto;
import com.emm.yixun.common.model.dto.HaveReceiveRefundDto;
import com.emm.yixun.common.model.dto.ImageDto;
import com.emm.yixun.common.model.dto.NeedReceiveRefundDto;
import com.emm.yixun.common.model.dto.PayDepositDto;
import com.emm.yixun.common.model.dto.PriceSchemeDetailDto;
import com.emm.yixun.common.model.dto.SignedDto;
import com.emm.yixun.common.model.dto.SubscribeDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.BusinessTypeEnum;
import com.emm.yixun.common.model.enums.CustomerStarEnum;
import com.emm.yixun.common.model.enums.CustomerStatusEnum;
import com.emm.yixun.common.model.enums.DocTypeEnum;
import com.emm.yixun.common.model.enums.ImgTypeEnum;
import com.emm.yixun.common.model.enums.IntentionLevelEnum;
import com.emm.yixun.common.model.enums.MemberTypeEnum;
import com.emm.yixun.common.model.enums.PayDepositBusinessStatusEnum;
import com.emm.yixun.common.model.enums.ReceivablesTypeEnum;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.model.enums.SexEnum;

@Service("getPayDepositDetailManage")
public class GetPayDepositDetailManage {

	@Autowired
	private CustomerService customerService;
	@Autowired
	private PayDepositService payDepositService;
	@Autowired
	private FamilyMemberService familyMemberService;
	@Autowired
	private AuditService auditService;
	@Autowired
	private UserService userService;
	@Autowired
	private PriceSchemeDetailService priceSchemeDetailService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private ProjectRoomService projectRoomService;
	@Autowired
	private HaveReceiveRefundService haveReceiveRefundService;
	@Autowired
	private PriceSchemeDetailMapper priceSchemeDetailMapper;
	@Autowired
	private PriceSchemeMapper priceSchemeMapper;
	@Autowired
	private NeedReceiveRefundService needReceiveRefundService;
	@Autowired
	private SubscribeService subscribeService;
	@Autowired
	private SignedService signedService;
	@Autowired
	private BaseCodeValueMapper baseCodeValueMapper;
	@Autowired
	private ImageService imageService;
	
	DecimalFormat df = new DecimalFormat("#.00");
	
	/**
	 * 客户认筹详情
	 * @param reqDto
	 * @return
	 */
	public GetPayDepositDetailResDto getPayDepositDetail(GetPayDepositDetailReqDto reqDto) {
		GetPayDepositDetailResDto resDto = new GetPayDepositDetailResDto();
		try{
			//1、客户认筹详情
			PayDepositDto payDepositDto = new PayDepositDto();
			payDepositDto.setMerchantId(reqDto.getMerchantId());
			if(!"1".equals(reqDto.getIsAudit())){
				payDepositDto.setProjectCode(reqDto.getProjectCode());
			}
			payDepositDto.setId(Long.parseLong(reqDto.getPayDepositId()));
			PayDepositDto getDepositDto = payDepositService.getPayDepositDetail(payDepositDto);
			if(getDepositDto == null){
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("无认筹详情!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			if(getDepositDto.getRoomId() != null && !"".equals(getDepositDto.getRoomId())){
				ProjectRoom room = projectRoomService.selectById(getDepositDto.getRoomId());
				if(room != null){
					String roomStatus = room.getRoomStatus();
					//可售或认筹状态可认筹
					if(!RoomStatusEnum.VENDIBILITY.getNo().equals(roomStatus) && !RoomStatusEnum.RESERVE.getNo().equals(roomStatus) && AuditStatusEnum.SUCCESS.getNo().equals(getDepositDto.getAuditStatus())){
						resDto.setPayDepositRoomType("0");
						resDto.setPayDepositRoomeMsg("房源暂不可售!");
					}
				}
			}else{
				if((AuditStatusEnum.SUCCESS.getNo().equals(getDepositDto.getAuditStatus()) && PayDepositBusinessStatusEnum.PAYDEPOSIT_PASS_SUBSCRIBE.getNo().equals(getDepositDto.getBusinessStatus())) 
						|| (AuditStatusEnum.SUCCESS.getNo().equals(getDepositDto.getAuditStatus())  && PayDepositBusinessStatusEnum.PAYDEPOSIT_PASS_SIGNED.getNo().equals(getDepositDto.getBusinessStatus()))){
					resDto.setPayDepositRoomType("0");
					resDto.setPayDepositRoomeMsg("本交易已转其他交易!");
				}else{
					//查询认筹是否已转认购
					SubscribeDto subscribeDto = new SubscribeDto();
					subscribeDto.setPayDepositId(getDepositDto.getId());
					Subscribe subscribe = subscribeService.selectByDto(subscribeDto);
					//查询认筹是否已转签约
					SignedDto signedDto = new SignedDto();
					signedDto.setPayDepositId(getDepositDto.getId());
					Signed signed = signedService.selectByDto(signedDto);
					
					if((subscribe != null && (AuditStatusEnum.SUCCESS.getNo().equals(subscribe.getAuditStatus()) || AuditStatusEnum.AUDIT.getNo().equals(subscribe.getAuditStatus())))
						|| (signed != null && (AuditStatusEnum.SUCCESS.getNo().equals(signed.getAuditStatus()) || AuditStatusEnum.AUDIT.getNo().equals(signed.getAuditStatus())))){
						resDto.setPayDepositRoomType("0");
						resDto.setPayDepositRoomeMsg("本交易已转其他交易!");
					}
				}		
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if(StringUtils.isNotEmpty(String.valueOf(getDepositDto.getRoomId()))){
				resDto.setRoomId(String.valueOf(getDepositDto.getRoomId()));
			}
			resDto.setIsPayDeposit(getDepositDto.getIsPaydeposit());
			if(StringUtils.isNotBlank(getDepositDto.getPayDepositHouses())){
				String combinedName = getDepositDto.getPayDepositHouses();
				int lastIndex = combinedName.lastIndexOf("-->");
				String roomName = combinedName.substring(lastIndex+3);
				resDto.setPayDepositHouses(roomName);
			}

			if(getDepositDto.getCalculateArea() != null){
				resDto.setCalculateArea(String.valueOf(getDepositDto.getCalculateArea()));
			}
			if(getDepositDto.getDiscountPrice() != null){
				resDto.setDiscountPrice(String.valueOf(getDepositDto.getDiscountPrice()));
			}
			if(getDepositDto.getDiscountTotalPrice() != null){
				/*String discountTotalPrice = df.format(Double.valueOf(String.valueOf(getDepositDto.getDiscountTotalPrice()))/10000);*/
				resDto.setDiscountTotalPrice(String.valueOf(getDepositDto.getDiscountTotalPrice()));
			}
			resDto.setPayDepositId(reqDto.getPayDepositId());
			resDto.setPayDepositCode(getDepositDto.getDepositCode());
			if(getDepositDto.getPayDepositAmount() != null){
				resDto.setPayDepositMoney(String.valueOf(getDepositDto.getPayDepositAmount()));
			}
			//业务状态
			resDto.setBusinessStatus(PayDepositBusinessStatusEnum.getByNo(getDepositDto.getBusinessStatus()).getDes());
			//需转成用户名（经纪人）
			resDto.setAgentId(getDepositDto.getAgentUser());
			//获取认筹客户信息
			Customer customer = customerService.selectById(getDepositDto.getCustomerId());
			resDto.setCustomerName(customer.getCustomerName());
			if(StringUtils.isNotEmpty(customer.getCustomerStar())){
				resDto.setCustomerStar(CustomerStarEnum.getByNo(customer.getCustomerStar()).getDes());
			}else{
				resDto.setCustomerStar(null);
			}
			if(StringUtils.isNotEmpty(customer.getCustomerSex())){
				resDto.setCustomerSex(SexEnum.getByNo(customer.getCustomerSex()).getDes());
			}
			resDto.setCustomerPhone(customer.getCustomerPhone());
			if(StringUtils.isNotEmpty(customer.getIntentionLevel())){
				resDto.setIntentionLevel(IntentionLevelEnum.getByNo(customer.getIntentionLevel()).getDes());
			}
			if(StringUtils.isNotEmpty(customer.getCustomerOrigin())){
				BaseCodeValue baseCodeValue = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getCustomerOrigin()));
				if(baseCodeValue != null){
					resDto.setCustomerOrigin(baseCodeValue.getCodeName());
				}
			}
			
			//客户状态
			if(StringUtils.isNotEmpty(customer.getCustomerStatus())){
				resDto.setCustomerStatus(CustomerStatusEnum.getByNo(customer.getCustomerStatus()).getDes());
			}
			if(getDepositDto.getDidTime() != null){
				resDto.setPayDepositDate(sdf.format(getDepositDto.getDidTime()));
			}
			resDto.setRemark(getDepositDto.getRemark());
			resDto.setAuditStatus(AuditStatusEnum.getByNo(getDepositDto.getAuditStatus()).getDes());
			if(StringUtils.isNotEmpty(customer.getPeDocumentType())){
				BaseCodeValue baseCodeValue_zjlx = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getPeDocumentType()));
				if(baseCodeValue_zjlx != null){
					resDto.setDocumentType(baseCodeValue_zjlx.getCodeName());
				}
			}
			resDto.setDocumentNumber(customer.getPeDocumentNumber());
			resDto.setMobile(customer.getCustomerPhone());
			resDto.setMailPost(customer.getPeContactAddress());
			resDto.setPostcode(customer.getPePostcode());
			//方案类别（0 低价；1 折扣）
			if(getDepositDto.getFloorType() != null && !"".equals(getDepositDto.getFloorType())){
				resDto.setFloorType(getDepositDto.getFloorType());
			}
			//折扣金额、折扣比例
			if("0".equals(getDepositDto.getFloorType())){
				resDto.setDiscountRate(String.valueOf(getDepositDto.getDiscountRate()));
				PriceScheme priceScheme = priceSchemeMapper.selectEntityByRoomId(getDepositDto.getRoomId());
				if(priceScheme != null){
					if("0".equals(priceScheme.getFloorType())){
						PriceSchemeDetailDto priceSchemeDetailDto = new PriceSchemeDetailDto();
						priceSchemeDetailDto.setPriceSchemeId(priceScheme.getId());
						priceSchemeDetailDto.setRoomId(getDepositDto.getRoomId());
						PriceSchemeDetail priceSchemeDetail = priceSchemeDetailService.selectByDto(priceSchemeDetailDto);
						BigDecimal t2 = new BigDecimal(100);
						if(priceSchemeDetail != null && priceSchemeDetail.getDiscountRate() != null){
							resDto.setDiscountRate(String.valueOf(priceSchemeDetail.getDiscountRate().divide(t2)));
						}else{
							resDto.setDiscountRate(null);
						}
					}
				}else{
					resDto.setDiscountRate(null);
				}
			}else{
				if(StringUtils.isNotEmpty(String.valueOf(getDepositDto.getRoomId()))){
					PriceSchemeDetail priceSchemeDetail = priceSchemeDetailService.selectEntityByRoomId(getDepositDto.getRoomId());
					if(priceSchemeDetail != null){
						BigDecimal t = new BigDecimal(1);
						BigDecimal t2 = new BigDecimal(100);
						if(priceSchemeDetail.getDiscountRate() != null && !"".equals(priceSchemeDetail.getDiscountRate())){
							BigDecimal discountRate = priceSchemeDetail.getDiscountRate().divide(t2);
							BigDecimal  zkbl = t.subtract(discountRate);
							BigDecimal zkjg = priceSchemeDetail.getTotalPrice().multiply(zkbl);
							resDto.setDiscountAmount(String.valueOf(zkjg));
							resDto.setDiscountRate(String.valueOf(discountRate));
						}else{
							resDto.setDiscountAmount(null);
							resDto.setDiscountRate(null);
						}
					}
				}
			}
			//获取最新的审核数据
			if(null != getDepositDto.getProcInstId()){
				List<HistoricActivityInstance> instances = historyService.createHistoricActivityInstanceQuery()
						.processInstanceId(getDepositDto.getProcInstId())
						.orderByHistoricActivityInstanceStartTime().desc().list();
				if (instances != null && instances.size() > 0) {
					boolean isEnd = true;
					List<HistoryTaskInfoListRes> userTaskList = new ArrayList<HistoryTaskInfoListRes>();
					for (HistoricActivityInstance historicActivityInstance : instances) {
						if (historicActivityInstance.getEndTime() != null) {// 过滤未审批的数据
							HistoryTaskInfoListRes htf = new HistoryTaskInfoListRes();

							if (historicActivityInstance.getActivityType().equals("startEvent")) {// 开始节点
								ProcessInstanceHistoryLog processInstanceHistoryLog = historyService
										.createProcessInstanceHistoryLogQuery(
												historicActivityInstance.getProcessInstanceId()).singleResult();
								htf.setTaskName("启动");
								htf.setTaskUserName(processInstanceHistoryLog.getStartUserId());
								htf.setTaskCheckStatus("发起");
								htf.setStartDate(historicActivityInstance.getStartTime());
								htf.setEndDate(historicActivityInstance.getEndTime());

								userTaskList.add(htf);
								continue;
							}

							if (historicActivityInstance.getActivityType().equals("endEvent")) {// 结束节点
								continue;
							}

							List<Comment> commentList = taskService.getTaskComments(historicActivityInstance
									.getTaskId());
							htf.setTaskName(historicActivityInstance.getActivityName());
							htf.setStartDate(historicActivityInstance.getStartTime());
							htf.setEndDate(historicActivityInstance.getEndTime());
							if (isEnd)// 为最后一个审批节点
								htf.setIsEnd(isEnd);
							if (null != commentList && commentList.size() > 0)
								htf.setTaskUserName(commentList.get(0).getUserId());//审核人
								htf.setAuditReason(commentList.get(0).getFullMessage());//审核意见
							userTaskList.add(htf);
							isEnd = false;
						}
					}

					if (userTaskList.size() > 0) {
						for (HistoryTaskInfoListRes historyTaskInfoVo : userTaskList) {
							if (historyTaskInfoVo.getTaskName().equals("启动")) {// 获取提交时间
//								payDepositDto.setSmTartTime(historyTaskInfoVo.getStartDate());
							}
							// 获取最后的审批人、审批时间、审批意见
							if (historyTaskInfoVo.getIsEnd() != null && historyTaskInfoVo.getIsEnd()) {
								UserDto userDto = new UserDto();
								userDto.setUserAccount(historyTaskInfoVo.getTaskUserName());
								User userEntity = userService.selectByDto(userDto);
								resDto.setAuditId(userEntity.getUserName());//审批人名称
								resDto.setAuditTime(sdf.format(historyTaskInfoVo.getEndDate()));//审批时间
								resDto.setAuditReason(historyTaskInfoVo.getAuditReason());//审批意见
							}
						}
					}
				}
			}else{
				UserDto userDto = new UserDto();
				userDto.setUserAccount(null);
				resDto.setAuditId(null);//审批人名称
				resDto.setAuditTime(null);//审批时间
				resDto.setAuditReason(null);//审批意见
			}
			
			//已收认筹金
			if(getDepositDto.getId() != null && !"".equals(getDepositDto.getId())){
				HaveReceiveRefundDto entity = new HaveReceiveRefundDto();
				entity.setRelationId(getDepositDto.getId());
				entity.setReceivablesType(ReceivablesTypeEnum.DEPOSIT.getNo());
				//当认筹转到认购或签约时,会变成转账状态.此处条件需去掉
				//entity.setTransferStatus(TransferStatusEnum.NORMAL.getNo());
				entity.setDocType(DocTypeEnum.COLLECTION.getNo());
				List<HaveReceiveRefund> resList = haveReceiveRefundService.selectListByDto(entity);
				BigDecimal realAmount = new BigDecimal("0");
				if(resList != null){
					for(int i = 0; i < resList.size(); i++){
						HaveReceiveRefund have = (HaveReceiveRefund)resList.get(i);
						realAmount = realAmount.add(have.getRealAmount());
					}
				}
				resDto.setRealAmount(String.valueOf(realAmount));
			}else{
				resDto.setRealAmount(null);
			}
			
			//2、获取家庭成员
			FamilyMemberDto fmDto = new FamilyMemberDto();
			fmDto.setBuyId(getDepositDto.getId());
			fmDto.setMemberType(MemberTypeEnum.DEPOSIT.getNo());
			List<FamilyMember> fmList = familyMemberService.selectListByDto(fmDto);
			List<CustomerFamilyListRes> customerFamilyList = new ArrayList<CustomerFamilyListRes>();
			if(fmList != null){
				for(FamilyMember fm: fmList){
					CustomerFamilyListRes cflRes = new CustomerFamilyListRes();
					cflRes.setMemberName(fm.getMemberName());
					if(StringUtils.isNotEmpty(fm.getDocumentType())){
						BaseCodeValue baseCodeValue_jtcy_zjlx = baseCodeValueMapper.selectEntityById(Long.valueOf(fm.getDocumentType()));
						if(baseCodeValue_jtcy_zjlx != null){
							cflRes.setDocumentType(baseCodeValue_jtcy_zjlx.getCodeName());
						}
					}
					cflRes.setDocumentNumber(fm.getDocumentNumber());
					customerFamilyList.add(cflRes);
				}
			}
			
			// 图片列表
			ImageDto imageDto = new ImageDto();
			imageDto.setMerchantId(getDepositDto.getMerchantId());
			imageDto.setUserCode(getDepositDto.getUserCode());
			imageDto.setObjectId(getDepositDto.getId());
			imageDto.setImgType(ImgTypeEnum.PAYDEPOSIT.getNo());
			List<Image> imageList = imageService.selectListByDto(imageDto);
			List<ImageListRes> imageListRes = new ArrayList<ImageListRes>();
			List<AnnexListRes> annexListRes = new ArrayList<AnnexListRes>();
			if (imageList.size() > 0 && imageList != null) {
				int annexNum = 0;
				for (Image image : imageList) {
					//gif|jpg|jpeg|png|bmp|GIF|JPG|JPEG|PNG|BMP图片后缀名格式
					String url_format = image.getSmallUrl();
					String url = url_format.substring(url_format.length()-3);
					String url2 = url_format.substring(url_format.length()-4);
					if("gif".equals(url) || "GIF".equals(url) || "jpg".equals(url) || "JPG".equals(url) 
						|| "png".equals(url) || "PNG".equals(url) || "bmp".equals(url) 
						|| "BMP".equals(url) || "jpeg".equals(url2) || "JPEG".equals(url2)){
						ImageListRes imageEntity = new ImageListRes();
						imageEntity.setImageId(String.valueOf(image.getId()));
						imageEntity.setTitle(image.getTitle());
						imageEntity.setLargeUrl(image.getLargeUrl());
						imageEntity.setNormalUrl(image.getNormalUrl());
						imageEntity.setSmallUrl(image.getSmallUrl());
						imageListRes.add(imageEntity);						
					}else{
						annexNum += annexNum+1;
						AnnexListRes annexEntity = new AnnexListRes();
						annexEntity.setAnnexName(image.getTitle());
						annexListRes.add(annexEntity);
					}
				}
				resDto.setAnnexNum(String.valueOf(annexNum));
				resDto.setAnnexList(annexListRes);
				resDto.setImageList(imageListRes);
			} else {
				resDto.setImageList(null);
			}
			
			//校验认筹金是否已经收满
			NeedReceiveRefundDto nrrDto = new NeedReceiveRefundDto();
			nrrDto.setRelationId(Long.parseLong(reqDto.getPayDepositId()));
			nrrDto.setBusinessType(BusinessTypeEnum.DEPOSIT.getNo());
			nrrDto.setDocType(DocTypeEnum.COLLECTION.getNo());
			nrrDto.setOrders(" t.create_time desc ");
			List<NeedReceiveRefund> needList = needReceiveRefundService.selectListByDto(nrrDto);
			if(needList != null && needList.size() > 0){
				BigDecimal big = new BigDecimal("0");
				HaveReceiveRefundDto entity = new HaveReceiveRefundDto();
				entity.setReceivablesId(needList.get(0).getId());
				List<HaveReceiveRefund> list = haveReceiveRefundService.selectListByDto(entity);
				for (HaveReceiveRefund refund : list) {
					big = big.add(refund.getRealAmount());
				}
				if(big.compareTo(needList.get(0).getTotalReceivablesAmount()) != 0){
					resDto.setEnough("0");
				}else{
					resDto.setEnough("1");
				}
			}
			
			resDto.setCustomerFamilyList(customerFamilyList);
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		}catch(Exception e){
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("获取认筹详情失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}
}
